package server;

import common.Novel;
import common.Request;
import common.Response;
import common.User;

import java.beans.XMLEncoder;
import java.io.*;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;

public class ServerThread implements Runnable {
    private final Socket s;

    public ServerThread(Socket s) {
        this.s = s;
    }


    //在线阅读功能，服务端把小说文本裁剪成固定字符数量，客户端直接传输需要哪本小说的名字（key为novelName），第几页(key为novelPages)过来，
    //返回数据：key为页数，值为字符串文件转化的字符串数组，可以多放几页比如（客户端需求第7页，服务端发送8,9，10...等等，客户端保存到HashMap中，客户端查不到的页数再发请求包）太麻烦了懒得写
    //就写简单的吧返回单页数据,key为content,一页有1024个字符
    public Response onlineRead(Request req) {
        Response resp = null;
        try {
            String fname = (String) req.get("novelName");
            ArrayList<Novel> novels = Novel.getNovels();
            for (Novel novel1 : novels) {
                if (novel1.getNovelName().equals(fname)) {
                    int pages = (int) req.get("novelPages");
                    resp = new Response(true);
                    resp.put("novel", novel1);
                    File f = new File("C:\\Novels\\" + fname + ".txt");
                    FileReader fr = new FileReader(f);
                    char[] buffer = new char[(int) f.length()];
                    fr.read(buffer);
                    char[] send = new char[1024];
                    System.arraycopy(buffer, (pages - 1) * 1024, send, 0, 1024);
                    resp.put("content", send);
                    fr.close();
                }
            }
            return resp;
        } catch (Exception e) {
            return new Response(false);
        }
    }

    //下载功能
    public Response download(Request req) {
        Response resp = null;
        try {
            String fname = (String) req.get("novelName");
            ArrayList<Novel> novels = Novel.getNovels();
            for (Novel novel1 : novels) {
                if (novel1.getNovelName().equals(fname)) {
                    resp = new Response(true);
                    resp.put("novel", novel1);
                    File f = new File("C:\\Novels\\" + fname + ".txt");
                    FileInputStream fis = new FileInputStream(f);
                    byte[] b = new byte[(int) f.length()];
                    fis.read(b);
                    resp.put("content", b);
                    fis.close();
                }
            }
        } catch (Exception e) {
            return new Response(false, "下载出现异常");
        }
        return resp;
    }


    //上传功能
    public Response upload(Request req) {
        try {
            Novel novel = (Novel) req.get("novel");
            String fname = novel.getNovelName();
            if (Novel.getNovels() == null) {
                ArrayList<Novel> novels = new ArrayList<>();
                novels.add(novel);
                byte[] b = (byte[]) req.get("content");
                File file=new File("C:\\Novels\\");
                file.mkdirs();
                File f=new File("C:\\Novels\\" + fname + ".txt");
                FileOutputStream fos = new FileOutputStream(f);
                fos.write(b);
                fos.close();
                XMLEncoder xe = new XMLEncoder(new FileOutputStream("novels.xml"));
                xe.writeObject(novels);
                xe.close();
            } else {
                ArrayList<Novel> novels = Novel.getNovels();
                if (Novel.getNovels() != null) {
                    for (Novel novel1 : novels) {
                        if (novel1.getNovelName().equals(fname)) {
                            return new Response(false, "小说已经存在,上传失败");
                        }
                    }
                }
                novels.add(novel);
                byte[] b = (byte[]) req.get("content");
                FileOutputStream fos = new FileOutputStream("C:\\Novels\\" + fname + ".txt");
                fos.write(b);
                fos.close();
                XMLEncoder xe = new XMLEncoder(new FileOutputStream("novels.xml"));
                xe.writeObject(novels);
                xe.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Response(false, "上传异常：" + e);
        }
        return new Response(true, "上传成功");
    }

    //获取小说列表功能
    public Response getNovelList(Request req) {
        ArrayList<Novel> novels = Novel.getNovels();
        Response resp = new Response(true);
        resp.put("NovelList", novels);
        return resp;
    }

    //登录功能
    public Response login(Request req) {
        Response resp = null;
        HashMap<String, Integer> users = User.getUsers();
        User user = (User) req.get("user");
        System.out.println(user.toString());
        if ((int) (users.get(user.getUname())) == (int) (user.getUpassword()) && user.getUname() != null) {
            resp = new Response(true, "登录成功");
        } else {
            resp = new Response(false, "账户或密码错误");
        }
        return resp;
    }

    //注册功能
    public Response register(Request req) {
        Response resp = null;
        User user = (User) req.get("user");
        HashMap<String, Integer> users = User.getUsers();
        if (users.containsKey(user.getUname())) {
            return new Response(false, "已存在的用户名");
        }
        users.put(user.getUname(), user.getUpassword());
        XMLEncoder xe = null;
        try {
            xe = new XMLEncoder(new FileOutputStream("users.xml"));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        xe.writeObject(users);
        xe.close();
        resp = new Response(true, "注册成功");
        return resp;
    }

    @Override
    public void run() {
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {
            ois = new ObjectInputStream(s.getInputStream());
            oos = new ObjectOutputStream(s.getOutputStream());
            while (true) {
                //开始对接，无限互发object流，判断流中的请求，进行处理返回Response
                Request req = (Request) ois.readObject();
                Response resp = null;
                try {
                    Method method = this.getClass().getDeclaredMethod(req.getAction(), Request.class);
                    resp = (Response) method.invoke(this, req);
                } catch (NoSuchMethodException e) {
                    resp = new Response(false, "此操作" + req.getAction() + "还不支持");
                } finally {
                    oos.writeObject(resp);
                    oos.reset();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println(s + "退出了");
            try {
                s.close();
            } catch (Exception e) {
            }
        }
    }
}

